package ma.dev.sowondejong.util;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.provider.MediaStore;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtil {

	
	public static byte[] bitmapToByteArray( @NotNull Bitmap bitmap ) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream() ;  
		bitmap.compress( CompressFormat.JPEG, 100, stream) ;  
		return stream.toByteArray() ;
	}
	
	public static Bitmap resizeBitmapImage(@NotNull Bitmap source, int maxResolution)
	{
		int width = source.getWidth();
		int height = source.getHeight();
		int newWidth = width;
		int newHeight = height;
		float rate = 0.0f;

		if(width > height)
		{
			if(maxResolution < width)
			{
				rate = maxResolution / (float) width;
				newHeight = (int) (height * rate);
				newWidth = maxResolution;
			}
		}
		else
		{
			if(maxResolution < height)
			{
				rate = maxResolution / (float) height;
				newWidth = (int) (width * rate);
				newHeight = maxResolution;
			}
		}

		return Bitmap.createScaledBitmap(source, newWidth, newHeight, true);
	}

	public static byte[] convertFiletoByte(String fullPath) {
		ByteArrayOutputStream bos = null;
		InputStream is ;

		try {

			is = new BufferedInputStream(new FileInputStream(fullPath));
			bos = new ByteArrayOutputStream();

			while(is.available() > 0) 
				bos.write(is.read());

			is.close();
			bos.close();

		}catch (IOException e) {
			e.printStackTrace();
		}

        if (bos != null) {
            return bos.toByteArray();
        }
    }

	@Nullable
    public static String getRealPathFromURI(@NotNull Uri contentUri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = SowonDejonApp.getContext().getContentResolver().query(contentUri, proj, null, null, null);

		if (cursor == null)
			return null;

		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

		cursor.moveToFirst();

		return cursor.getString(column_index);
	}

}
